// pages/searcher/searchHistory/searchHistory.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 自定义导航栏的高度
    statusBarHeight: getApp().globalData.statusBarHeight,
    navBarHeight: getApp().globalData.navBarHeight,
    hiddenResultList: true,
    focusTrue: true,
    focusIndex: 0,
    keywords: "",
    keywordsTips: "",
    searchHistorys: [], //"腊猪脚", "大米", "西瓜", "烧烤", "理发", "包子"
    searchMaybeLikes: [], //"重庆印象火锅", "腊猪脚", "大米", "西瓜", "烧烤", "理发", "包子"
    searchKeywordsResultList: [] //"重庆印象火锅", "腊猪脚", "大米", "西瓜", "烧烤", "理发", "包子"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    var pageObj = this
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('acceptDataFromOpenerPage', function (param) {
      // console.error("参数：" + JSON.stringify(param))
      pageObj.setData({ keywordsTips: param.keywords })
      // console.error("参数data：" + JSON.stringify(pageObj.data))
      // 获取推荐关键字
      pageObj.getHotKeywords()
    })

    // 查询历史
    const searchHistorysCache = wx.getStorageSync('searchHistorys');
    if (searchHistorysCache != null) {
      pageObj.setData({ searchHistorys: JSON.parse(searchHistorysCache) })
    }
  },
  getHotKeywords() {
    var that = this
    // const token = wx.getStorageSync('token')
    const preUrl = getApp().globalData.SERVER_URL
    const url = preUrl + "fc/searchKeyword/client/anon/listForHotKeywords"
    wx.request({
      url: url,
      method: 'GET',
      data: {
        district: "",
        pageNo: 1,
        pageSize: 10
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
        // 'X-Access-Token': token
      },
      success(res: any) {
        // console.error("结果: " + JSON.stringify(res))
        // wx.stopPullDownRefresh()
        if (res.data.code == 200) {
          that.setData({ searchMaybeLikes: res.data.result.records })
          // console.error("结果: searchMaybeLikes = " + JSON.stringify(that.data.searchMaybeLikes))
        } else {
          console.info(JSON.stringify(res))
        }
      },
    })
  },
  searchKeywordsList(keywords: string) {
    var that = this
    // const token = wx.getStorageSync('token')
    const preUrl = getApp().globalData.SERVER_URL
    const url = preUrl + "fc/searchKeyword/client/anon/getKeywordsByKeyword"
    wx.request({
      url: url,
      method: 'GET',
      data: {
        keyword: keywords,
        pageNo: 1,
        pageSize: 10
      },
      // header: {
      //   'content-type': 'application/x-www-form-urlencoded', // 默认值
      //   // 'X-Access-Token': token
      // },
      success(res: any) {
        // console.error("结果: " + JSON.stringify(res))
        // wx.stopPullDownRefresh()
        if (res.data.code == 200) {
          that.setData({ searchKeywordsResultList: res.data.result.records })
          console.error("结果: searchKeywordsResultList = " + JSON.stringify(that.data.searchKeywordsResultList))
        } else {
          console.info(JSON.stringify(res))
        }
      },
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({ focusTrue: true, hiddenResultList: true })

    if (this.data.keywords.length != 0) {
      this.setData({ focusIndex: this.data.keywords.length })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setData({ keywordsTips: this.data.keywords })
    this.setData({ keywords: '' })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },
  doBack() { //返回事件
    wx.navigateBack()
  },
  bindinputEvevnt(event: any) {// 输入框1 输入触发
    const keywords: string = event.detail.value
    if (keywords == null || keywords.length == 0) {// 输入内容为空
      this.setData({ keywords: '', hiddenResultList: true })
    } else {
      this.setData({ keywords: keywords, hiddenResultList: false })
      // 查询关键字列表
      this.searchKeywordsList(keywords)
    }
    console.error("输入触发时间: " + keywords)
  },
  bindfocusEvevnt() {// 输入框2 获取焦点

    // this.setData({ keywords: this.data.keywordsTips})

    if (this.data.keywords.length > 0) {// 有值时，才显示搜索关键字列表
      this.setData({ hiddenResultList: false, focusTrue: true })
    } else {
      this.setData({ hiddenResultList: true, focusTrue: true })
    }

    console.error("事件-输入框2 获取焦点" + this.data.keywords)
  },
  bindblurEvevnt() {// 输入框3 失去焦点
    this.setData({ hiddenResultList: true })
    console.error("事件-输入框3 失去焦点")
  },

  doSearch(event: any) {// 点击软盘确定按键
    var keywords: string = event.detail.value
    if (keywords.length == 0) {
      keywords = this.data.keywordsTips
    }
    console.error("keywords: " + keywords)
    this.gotoSearchResultPage(keywords)

    this.setData({ keywords: keywords, keywordsTips: keywords })
  },
  doClearAllHistory() {// 点击清除历史
    this.setData({ searchHistorys: [] })
    wx.setStorageSync('searchHistorys', "");
  },
  doClearInputKeyword() {// 点击清除输入
    console.error("点击清除输入")
    this.setData({ hiddenResultList: true, keywords: "", keywordsTips: "" })
  },
  clickKeywordsSearch(param: any) {// 点击历史关键字
    let keywords = param.currentTarget.dataset.keywords
    console.error("keywords: " + keywords)
    this.gotoSearchResultPage(keywords)
    this.setData({ keywords: keywords, keywordsTips: keywords })
  },
  gotoSearchResultPage(value: string): void {// 调到查询页
    this.data.searchHistorys = this.data.searchHistorys.filter(item => item !== value);// 移除指定元素
    this.data.searchHistorys.unshift(value)// 加到第一位
    wx.setStorageSync('searchHistorys', JSON.stringify(this.data.searchHistorys));

    wx.navigateTo({
      url: '/pages/searcher/searchResult/searchResult',
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { keywords: value })
      }
    })

    // 查询历史
    const searchHistorysCache = wx.getStorageSync('searchHistorys');
    if (searchHistorysCache != null) {
      this.setData({ searchHistorys: JSON.parse(searchHistorysCache) })
    }
    this.setData({ hiddenResultList: true })
  },
})